package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.leyou.common.pojo.PageResult;
import com.leyou.enums.ExceptionEnum;
import com.leyou.exception.LyException;
import com.leyou.item.mapper.BrandMapper;

import com.leyou.item.pojo.Brand;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;


import java.util.List;


/**
 * 品牌实现类
 */
@Service
public class BrandService {

    @Autowired
    public  BrandMapper brandMapper;

    /**
     * 分页品牌查询
     * @param page  当前页，int
     * @param rows   每页大小，int
     * @param sortBy 排序字段，String
     * @param desc 是否为降序，boolean
     * @param key  搜索关键词，String
     * @return
     */
    public PageResult<Brand> queryBrandByPage(
            Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        // 开始分页
        PageHelper.startPage(page, rows);
        // 过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().andLike("name", "%" + key + "%")
                    .orEqualTo("letter", key);
        }
        if (StringUtils.isNotBlank(sortBy)) {
            // 排序
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }
        // 查询
        Page<Brand> pageInfo = (Page<Brand>) brandMapper.selectByExample(example);
        // 返回结果
        return new PageResult<>(pageInfo.getTotal(), pageInfo);
    }

    public void saveBrand(Brand brand, List<Long> ids) {
        //新增品牌
        this.brandMapper.insert(brand);
        //新增品牌和分类中间表
        //增强for（元素类型 变量:数组或者集合）
        for (Long cid : ids) {
            this.brandMapper.insertCategoryBrand(cid,brand.getId());
        }
    }


    /**
     * 根据主键id查询商品品牌
     * @param id
     * @return
     */
    public Brand queryById(Long id){
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }

    /**
     *根据cid查询品牌列表
     * @param cid
     * @return
     */
    public List<Brand> queryBrandByCid(Long cid) {
        List<Brand> list = brandMapper.queryByCategoryId(cid);
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }

        return list;
    }
}
